import { ref, onMounted } from 'vue'
import { get, mapValues } from 'lodash'
import * as api from '@/api/dict'
import { Option } from '@/components/Form/types'
import { DictId, FormItemKey } from 'typings/interfaces'
import { $Keys } from 'typings/util'

type Params = Record<FormItemKey, DictId>

type Options<T extends Params> = Record<$Keys<T>, Option[]> | Record<string, Option[]>

const useOptions = <P extends Params>(params: P) => {
  const options = ref<Options<typeof params>>({})
  const loading = ref<boolean>(false)
  const dictIds = Object.values(params)
  onMounted(() => {
    loading.value = true
    api
      .dataDictionary(dictIds)
      .then(({ data }) => {
        loading.value = false
        Object.assign(
          options.value,
          mapValues<Params, Option[]>(params, (value) => get(data, ['data', value], []))
        )
      })
      .catch(() => (loading.value = false))
  })

  return {
    loading,
    options,
  }
}

export default useOptions
